import request from '@/utils/request'
const defDomainCode = 'marketing'
const defAppCode = 'top2-crm'

/**
 * 根据字典类型查询字典
 * @param {string} dictTypeCode 数据字典编码
 * @param {string} appCode 应用编码
 * @param {string} domainCode 业务域编码
 * @returns {Array} 数据字典值列表
 * */
export const getDictList = async(dictTypeCode) => {
  const data = await getDictByType({ dictTypeCode })
  return data
}
/**
 * 根据字典类型查询字典
 * @param {string} dictTypeCode 数据字典编码
 * @param {string} appCode 应用编码
 * @param {string} domainCode 业务域编码
 * @returns {Array} 数据字典值列表
 * */
export const getDictByType = async({ dictTypeCode, appCode = defAppCode, domainCode = defDomainCode }) => {
  const key = `${domainCode}_${appCode}_${dictTypeCode}`
  let data = sessionStorage.getItem(key)
  if (data) {
    try {
      data = JSON.parse(data)
      return data
    } catch (error) {
      console.log(error)
    }
  }
  const res = await request({
    url: `/data-dict/app/v2/dictionary/${dictTypeCode}`,
    method: 'get',
    params: {
      appCode,
      domainCode
    },
    loading: false
  })
  let resData = []
  if (res && res.data) {
    resData = res.data.sort((a, b) => { return a.sort - b.sort })
  }
  try {
    sessionStorage.setItem(key, JSON.stringify(resData))
  } catch (error) {
    console.log(error)
  }
  return resData
}

/**
 * 根据字典类型批量查询字典值列表
 * @param {Array} dictTypeCodes 数据字典编码
 * @returns {Array} 数据字典值列表
 * */
export const getDictByPatchType = async({ dictTypeCodes, appCode = defAppCode, domainCode = defDomainCode }) => {
  const res = await request({
    url: `/data-dict/app/v2/dictionary/patch/dictTypeCode`,
    method: 'post',
    params: {
      appCode,
      domainCode
    },
    data: dictTypeCodes,
    loading: false
  })
  return res && res.data
}

/**
 * 根据字典父类型与父编码查询子级数据字典
 * @param {String} parentDictTypeCode 父字段类型编码
 * @param {String} parentDictCode 父字典编码
 * @param {string} appCode 应用编码
 * @param {string} domainCode 业务域编码
 * @returns {Array} 数据字典值列表
 * */
export const getDictChildByCode = async({ parentDictTypeCode, parentDictCode, dictTypeCode, appCode = defAppCode, domainCode = defDomainCode }) => {
  const data = new FormData()
  data.append('appCode', appCode)
  data.append('domainCode', domainCode)
  data.append('parentDictCode', parentDictCode)
  data.append('parentDictTypeCode', parentDictTypeCode)
  const res = await request({
    url: `/data-dict/app/v2/dictionary/child`,
    method: 'post',
    data,
    loading: false
  })
  return res && res.data
}

// 获取省列表(移动端各应用独立接口)
export function getProvinces() {
  return request({
    url: '/app/v1/administrativeDivisions/provinces',
    method: 'get',
    loading: false
  })
}

// 获取市、区县、街道列表(移动端各应用独立接口)
export function getAreaList(parentId) {
  return request({
    url: '/app/v1/administrativeDivisions',
    method: 'get',
    params: { parentId },
    loading: false
  })
}
